$(document).ready(function () {
	
	addtabs();
})	
function addtabs(){	 
	var  typetabs=$("#type_tabs");
	var url='/bloseWeight/getMoshi';
	var reData = common_ajax.ajaxFunc(url,null,"json");
	for(var i=0;i<reData.length;i++)
	{
		
		var opts = {
				title :reData[i].name,
				id:reData[i].orderid,
				closable : false,
//					iconCls : node.iconCls,
				content :
					'<table id="pattern_'+reData[i].orderid+'" class="easyui-datagrid" style="width:100%;">'+
							
					'</table>'	+
					'<a id="save_a" href="javascript:void(0);" class="easyui-linkbutton" data-options="iconCls:'+"'icon-save'"+'"  style="margin-top: 10px;margin-left: 90%;" onclick="save()">保存</a>',
				collapsible:true,
				fit : true
			};
		if (typetabs.tabs('exists', reData[i].name)) {
			typetabs.tabs('select', reData[i].name);
		} else {
			typetabs.tabs('add', opts);
		}
//		
		//列表
		list(reData[i].ids,reData[i].orderid);
	}

}
//获取模式下的list
function  list(moshiIds,orderid)
{
	var columns = [[
					{field:'schedule',title:'排期',width:100,align:'center'},
					{field:'starttime',title:'起始日期',width:100,align:'center'},
					{field:'endtime',title:'截止日期',width:100,align:'center'},
					{field:'plantostorenum',title:'计划到店次数',width:100,align:'center',editor:'numberspinner'},
					{field:'delweitarget',title:'减重目标',width:100,align:'center',editor:'numberspinner'}
			    ]];
	//通过ids获取模式下排期数据
	var url='/bloseWeight/getSchedule';
	var data={"moshiIds":moshiIds};
	var reData = common_ajax.ajaxFunc(url,data,"json");
	var data=[];
	var registTime=$("#customerRegisttime").val();
	if(registTime != "")
	{	
//		var hybh=$("#customerHybh").val();
//		$("#customerHybh").textbox('setValue',hybh);
//		getTime($("#customerRegisttime").val());

		for(var j=0;j<reData.length;j++)
		{	
			var arr = reData[j].name.split('-');
			var starattime=arr[0];
			var endtime=arr[1];
			var st=load(registTime,starattime);
			data.push({"schedule":reData[j].name,"starttime":load(registTime,starattime),"endtime":load(registTime,endtime),"plantostorenum":"","delweitarget":""});
		}
	}else
	{
		for(var j=0;j<reData.length;j++)
		{	
			data.push({"schedule":reData[j].name,"starttime":"","endtime":"","plantostorenum":"","delweitarget":""});
		}
	}
	
	var tabid='#pattern_'+orderid;
	$(tabid).datagrid({
		 fitColumns:true,
		iconCls:'icon-edit',
		singleSelect: true,
		rownumbers: true, //显示序号
		columns: columns,
		data: data,
		onClickRow: onClickRow
	});
}
function  load(date,days)
{	
		date.setDate(date.getDate()+days); 
		var month=date.getMonth()+1; 
		var day = date.getDate(); 
		if(month<10){ 
		month = "0"+month; 
		} 
		if(day<10){ 
		day = "0"+day; 
		} 
		var val = date.getFullYear()+"/"+month+"/"+day; 
		return val;
}

//获取顾客信息
function  getCusInfo()
{
	var hybh=$('#customerHybh').val();
	var name=$('#customerName').val();
	var phone=$('#customerPhone').val();
	$("#customerHybh").textbox('setValue',hybh);
	
	if(hybh !="" || name !="" || phone !="")
	{
	
		var url='/bentryRegister/getCusByHybh';
		var data={"hybh":hybh,"name":name,"phone":phone};
		var reData = common_ajax.ajaxFunc(url,data);
		var daJson=$.parseJSON(reData);
		var msg=daJson.msg;
		if(msg=="200")
		{
//					$("#customerIds").val(daJson.customer.ids);
			$("#customerName").textbox('setValue',daJson.customer.name);
			$("#customerPhone").textbox('setValue',daJson.customer.phone);
			$("#customerHybh").textbox('setValue',daJson.customer.hybh);
			searchInfo();
			var url1='/bloseWeight/selDelWTByCId';
			var data1={"customerIds":daJson.customer.ids};
			var reData1 = common_ajax.ajaxFunc(url1,data1);
			var daJson1=$.parseJSON(reData1);
			if(daJson1=="")
			{	
				getTime(daJson.customer.registtime);
			}else
			{
				$('#pattern_'+daJson1[0].types).datagrid('loadData',daJson1);  
				$("#type_tabs").tabs('selectById', daJson1[0].types);
			}
//					getTime(daJson.customer.registtime);
		}else if(msg=="201")
		{
			 $.alert(parent.$, "查询失败，请重新输入查询条件");
		}else
		{
			 $.alert(parent.$,msg);
		}
	
	}
}


	function   save()
	{	
		
		var current_tab = $("#type_tabs").tabs('getSelected');
		var t=current_tab.panel('options').id;
		var da="#pattern_"+t;
		$(da).datagrid('endEdit', editIndex);
		var rows=$(da).datagrid("getRows");
		var rowjson=JSON.stringify(rows);
		var customerName=$('#customerName').val();
		var customerSfzhm=$('#customerSfzhm').val();
		var customerHybh=$('#customerHybh').val();
		if(customerName!="" && customerSfzhm!="" && customerHybh!="")
		{
			var url="/bloseWeight/saveDelWeiTarget";
			var data={"customerHybh":customerHybh,"lbbh":t,"delWeiInfo":rowjson};
			var reData = common_ajax.ajaxFunc(url, data);
			
			if(reData == "upsuccess")
			{
				 $.slideMsg("更新成功", parent.$);
			}
			else if(reData=="success")
			{		
					
					 $.slideMsg("保存成功", parent.$);
//					 var cusIds=$('#customerIds').val();
//					 parent.nodeClick("减重目标管理",'/bloseWeight?cusIds='+cusIds);
			}else
			{
				$.alert(parent.$,reData );
////				
			}
		}else
		{
			 $.alert(parent.$, "请先输入姓名和身份证！！");
		}
	}
	
	var editIndex = undefined;
	function endEditing(obj){
		if (editIndex == undefined){return true}
		if (obj.datagrid('validateRow', editIndex)){
				obj.datagrid('endEdit', editIndex);
			editIndex = undefined;  
			return true;
		}
		else {
			return false;
		}
	}
	
	function onClickRow(index){
		if (editIndex != index){
			if (endEditing($(this))){
				$(this).datagrid('selectRow', index);
				$(this).datagrid('beginEdit', index);
				editIndex = index;
			} else {
				$(this).datagrid('selectRow', editIndex);
			}
		}
		
	}
	//--------------
	$.extend($.fn.tabs.methods, {
	    getTabById: function(jq,id) {
	        var tabs = $.data(jq[0], 'tabs').tabs;
	        for(var i=0; i<tabs.length; i++){
	            var tab = tabs[i];
	            if (tab.panel('options').id == id){
	                return tab;
	            }
	        }
	        return null;
	    },
	    selectById:function(jq,id) {
	        return jq.each(function() {
	            var state = $.data(this, 'tabs');
	            var opts = state.options;
	            var tabs = state.tabs;
	            var selectHis = state.selectHis;
	            if (tabs.length == 0) {return;}
	            var panel = $(this).tabs('getTabById',id); // get the panel to be activated 
	            if (!panel){return}
	            var selected = $(this).tabs('getSelected');
	            if (selected){
	                if (panel[0] == selected[0]){return}
	                $(this).tabs('unselect',$(this).tabs('getTabIndex',selected));
	                if (!selected.panel('options').closed){return}
	            }
	            panel.panel('open');
	            var title = panel.panel('options').title;        // the panel title 
	            selectHis.push(title);        // push select history 
	            var tab = panel.panel('options').tab;        // get the tab object 
	            tab.addClass('tabs-selected');
	            // scroll the tab to center position if required. 
	            var wrap = $(this).find('>div.tabs-header>div.tabs-wrap');
	            var left = tab.position().left;
	            var right = left + tab.outerWidth();
	            if (left < 0 || right > wrap.width()){
	                var deltaX = left - (wrap.width()-tab.width()) / 2;
	                $(this).tabs('scrollBy', deltaX);
	            } else {
	                $(this).tabs('scrollBy', 0);
	            }
	            $(this).tabs('resize');
	            opts.onSelect.call(this, title, $(this).tabs('getTabIndex',panel));
	        });
	    },
	    existsById:function(jq,id){
	        return $(jq[0]).tabs('getTabById',id) != null;
	    }
	});
